﻿using FuelAbp.Entities;
using FuelAbp.Inputs;
using FuelAbp.Outputs;
using FuelDXApplication1.Entity;
using HtmlAgilityPack;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Mail;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.Application.Dtos;
using Volo.Abp.Application.Services;
using static FuelAbp.MksService.FuelSynchronizationService;

namespace FuelAbp.MksService
{
    [ApiExplorerSettings(GroupName = "v2")]
    public class FuelSynchronizationService: ApplicationService
    {
        public readonly ISqlSugarClient db;

        public FuelSynchronizationService(ISqlSugarClient db) 
        {
            this.db = db;
        }

        /// <summary>
        /// 燃料参数同步
        /// </summary>
        /// <returns></returns>
        public async Task<object> GetFuelInfo()
        {

            var list = await db.Queryable<FuelParameters>().ToListAsync();
            if (list == null)
            {
                return UnitiveResult<string>.Error("请求失败");
            }
            return UnitiveResult<List<FuelParameters>>.Success(list);

        }

        /// <summary>
        /// 基本信息添加
        /// </summary>
        /// <param name="basicInformation"></param>
        /// <returns></returns>
        public async Task<object> AddBasicInform(BasicInformation basicInformation)
        {

            var reuslt = await db.Insertable(basicInformation).ExecuteCommandAsync();
            if (reuslt > 0)
            {
                return UnitiveResult<string>.Success("添加成功");
            }
            return UnitiveResult<string>.Success("添加失败");

        }

        /// <summary>
        /// 批量基本信息添加
        /// </summary>
        /// <param name="basicInformation"></param>
        /// <returns></returns>
        public async Task<object> AddBasicInforms(List<BasicInformation> basicInformation)
        {


            var reuslt = await db.Insertable(basicInformation).ExecuteCommandAsync();
            if (reuslt > 0)
            {
                return UnitiveResult<string>.Success("添加成功");
            }
            return UnitiveResult<string>.Success("添加失败");

        }

        #region

        ///// <summary>
        ///// 获取节假日信息添加到数据库
        ///// </summary>

        //public object GetInfo(string daterrd)
        //{
        //    int n = 0;
        //    using HttpClient client = new HttpClient();

        //    var srsfdsa = daterrd;

        //    client.BaseAddress = new Uri($"https://www.gov.cn/zhengce/zhengceku/{srsfdsa}/content_6911528.htm");

        //    var reposons = client.GetAsync("").Result;
        //    if (reposons.IsSuccessStatusCode)
        //    {
        //        var result = reposons.Content.ReadAsStringAsync().Result;
        //        HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
        //        doc.LoadHtml(result);

        //        var titeltitles = doc.DocumentNode.SelectNodes("//*[@id=\"UCAP-CONTENT\"]/div/p");
        //        foreach (var titel in titeltitles)
        //        {
        //            Console.WriteLine(titel.InnerText);
        //            var title = titel.InnerText;
        //            var startDate = ParseDate(title); // 你需要实现这个日期解析方法
        //            var endDate = ParseEndDate(title); // 你需要实现这个日期解析方法

        //            var holiday = new Holiday
        //            {
        //                HolidayName = title,
        //                StartDate = startDate,
        //                EndDate = endDate
        //            };

        //            n = db.Insertable(holiday).ExecuteCommand();
        //        }
        //    }

        //    return n;

        //}

        //private DateTime ParseDate(string title)
        //{
        //    // 实现日期解析逻辑
        //    return DateTime.MinValue;
        //}

        //private DateTime ParseEndDate(string title)
        //{
        //    // 实现日期解析逻辑
        //    return DateTime.MinValue;
        //}
        #endregion

        /// <summary>
        /// 日期同步
        /// </summary>
        /// <returns></returns>
        public async Task<object> GetHoiaday()
        {

            var list = await db.Queryable<Holiday>().ToListAsync();
            if (list == null)
            {
                return UnitiveResult<string>.Error("请求失败");
            }
            return UnitiveResult<List<Holiday>>.Success(list);

        }

        /// <summary>
        /// 远程查询
        /// </summary>
        /// <returns></returns>
        public async Task<object> GetBase(PageGetBase pageGetBase) 
        {

            var baseinfolist = await db.Queryable<BasicInformation, FuelType, VehicleTypeInFo>((o, i, c) => new JoinQueryInfos(
                        JoinType.Inner, o.FuelTypeId == i.FuelTypeId, //左连接 左链接 左联 
                        JoinType.Inner, o.VersionId == c.VehicleTypeId
                        )).Select((o, i, c) => new RemoteInfoOutPuts
                        {


                            FuelParameter = o.FuelParameter,
                            IsImportedCars = o.IsImportedCars,
                            AutomobileManufacturers = o.AutomobileManufacturers,
                            Dealer = o.Dealer,
                            DetectionName = o.DetectionName,
                            ReportNo = o.ReportNo,
                            ICPRecordNumber = o.ICPRecordNumber,
                            VehicleModel = o.VehicleModel,
                            VersionId = o.VersionId,
                            DrivingType = o.DrivingType,
                            Quality = o.Quality,
                            TopSpeed = o.TopSpeed,
                            TyrSpecification = o.TyrSpecification,
                            Wheelbase = o.Wheelbase,
                            DateOfImport = o.DateOfImport,
                            GenericName = o.GenericName,
                            TypeIdName = o.TypeIdName,
                            NumberOfSeats = o.NumberOfSeats,
                            MaximumTotalDesignMass = o.MaximumTotalDesignMass,
                            RatedCapacity = o.RatedCapacity,
                            Tread = o.Tread,
                            FuelTypeId = o.FuelTypeId,
                            FeedbackCode = o.FeedbackCode,
                            Status = o.Status,
                            DatInfo = o.DatInfo,
                            FuelTypeName = i.FuelTypeName,
                            VehicleTypeId = c.VehicleTypeId,
                            VehicleTypeName = c.VehicleTypeName,


                        }).ToListAsync();

            int TotalCount = baseinfolist.Count();

            int PageCount = (int)Math.Ceiling(baseinfolist.Count() * 1.0 / pageGetBase.pageSize);



            var pageINfoFan = baseinfolist.OrderBy(x => x.FuelParameter).Skip((pageGetBase.pageIndex - 1) * pageGetBase.pageSize).Take(pageGetBase.pageSize).ToList();

            //if (pageINfoFan != null)
            //{
            //    return UnitiveResult<List<RemoteInfoOutPuts>>.Success(pageINfoFan);
            //}

            //return GuiTouApiResult<List<RemoteInfoOutPuts>>.Success(pageINfoFan, PageCount, TotalCount);

            GuiTouApiResult<List<RemoteInfoOutPuts>> result = new GuiTouApiResult<List<RemoteInfoOutPuts>>(200, "success", pageINfoFan);
            result.TotalCount = TotalCount;
            result.PageCount = PageCount;

            //return UnitiveResult<string>.Success("失败") ;

            return result;



        }

        /// <summary>
        /// 发送邮件
        /// </summary>
        /// <param name="args"></param>
        public  void Main(string[] args)
        {
            //实例化一个发送邮件类。
            MailMessage mailMessage = new MailMessage();
            //发件人邮箱地址，方法重载不同，可以根据需求自行选择。
            mailMessage.From = new MailAddress("2966066399@qq.com");
            //收件人邮箱地址。
            mailMessage.To.Add(new MailAddress("1780162681@qq.com"));
            //抄送人邮箱地址。
            //message.CC.Add(sender);
            //邮件标题。
            mailMessage.Subject = "发送邮件测试";
            //邮件内容。
            mailMessage.Body = "我上早八";
            //是否支持内容为HTML。
            //mailMessage.IsBodyHtml = true;
            //实例化一个SmtpClient类。
            SmtpClient client = new SmtpClient();
            client.Port = 587;
            //在这里使用的是qq邮箱，所以是smtp.qq.com，如果你使用的是126邮箱，那么就是smtp.126.com。
            //client.Host = "smtp.163.com";
            client.Host = "smtp.qq.com";
            //使用安全加密连接（是否启用SSL）
            client.EnableSsl = true;
            //设置超时时间
            //client.Timeout = 10000; 163授权码：MDpzg6diQMqdwsQE
            //不和请求一块发送。 QQ授权码:
            client.UseDefaultCredentials = false; //
            //验证发件人身份(发件人的邮箱，邮箱里的生成授权码);
            client.Credentials = new NetworkCredential("2966066399@qq.com", "xeccabpvaetodeaa");//szcodirtgvjgbfii
            //网易邮箱客户端授权码DJURBEKTXEWXQATX
            //client.Credentials = new NetworkCredential("liulijun3236@163.com", "ZAJDNCKWHUBHQIMY");
            try
            {
                //发送
                client.Send(mailMessage);
                //发送成功
            }
            catch (Exception)//发送异常
            {
                //发送失败
                //System.IO.File.WriteAllText(@"C:\test.txt", e.ToString(), Encoding.UTF8);
            }
        }

    }

}
